package admin_user_api

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/res"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

func (AdminUserApi) UserDel(c *gin.Context) {
	var delReq models.DeleteRequest
	if err := c.ShouldBindJSON(&delReq); err != nil {
		logrus.Error(err)
		panic(err)
	}
	var userList []models.UserModel
	err := global.DB.Find(&userList, delReq.IdList).Error
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	err = global.DB.Transaction(func(tx *gorm.DB) error {
		// 先删除用户收藏文章关联表
		if err := tx.Model(&userList).Association("CollModels").Clear(); err != nil {
			return err
		}
		// 再删除用户
		if err := tx.Delete(&userList).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	res.Ok("删除成功", len(userList), c)
}
